package com.tengju.bff.interfaces.openapi;

import com.tengju.bff.interfaces.app.withdraw.facade.ServiceFeeFacade;
import com.tengju.bff.interfaces.openapi.facade.LetaxFacade;
import com.tengju.bff.interfaces.openapi.vo.IdentityAuthRequest;
import com.tengju.bff.interfaces.openapi.vo.LetaxResponse;
import com.tengju.bff.interfaces.openapi.vo.RegResultNotifyRequest;
import com.tengju.bff.interfaces.shared.servlet.NotTokenValid;
import com.tengju.settlement.domain.model.account.UserIdCode;
import com.tengju.user.domain.shared.JsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@Api(tags = "乐税回调接口")
@RequestMapping(value = "/openapi/letax/")
public class LetaxOpenApiController {

    private final LetaxFacade letaxFacade;

    private final ServiceFeeFacade serviceFeeFacade;

    @Autowired
    public LetaxOpenApiController(LetaxFacade letaxFacade, ServiceFeeFacade serviceFeeFacade) {
        this.letaxFacade = letaxFacade;
        this.serviceFeeFacade = serviceFeeFacade;
    }

    @ApiOperation(value = "身份认证", notes = "身份认证")
    @RequestMapping(value = "identityAuth", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @NotTokenValid
    public LetaxResponse identityAuth(@RequestBody IdentityAuthRequest data) {
        log.info("乐税身份认证参数: {}", JsonUtil.toJSONString(data));
        try {
            // TODO 参数加密
            return letaxFacade.identityAuth(data);
        } catch (Exception e) {
            log.error("identityAuth err", e);
            return LetaxResponse.error("乐税身份认证失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "乐税工商注册成功异步回调", notes = "工商注册完成异步通知，匹配身份证时候相等")
    @RequestMapping(value = "eventCompleteNotify", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @NotTokenValid
    public LetaxResponse eventCompleteNotify(@RequestBody RegResultNotifyRequest data) {
        // TODO 参数加密
        log.info("乐税工商注册完成异步通知参数：{}", JsonUtil.toJSONString(data));
        if (null == data) {
            log.error("乐税工商注册完成异步通知参数为空");
            return LetaxResponse.error("入参为空");
        }

        serviceFeeFacade.updateRegisteredStatus(new UserIdCode(Long.parseLong(data.getBody().getEventContent().getCoreCompanyMerchantId())));

        return LetaxResponse.builder()
                .head(LetaxResponse.Head.builder()
                        .rtnCode("00")
                        .rtnMsg("请求成功")
                        .build())
                .build();

    }

}
